ASP.NET Sessions

Sessions can also be used to store complex data for users, such as cookies In fact, the session will use cookies to store data, unless you explicitly tell it. Session can be easily used in session with ASP.NET. We will reuse the cookie example and will use the session instead. However keep in mind, that sessions will end after a few minutes, as is configured in the web.config file. Markup Code:


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Sessions</title>
</head>
<body runat="server" id="BodyTag">
    <form id="form1" runat="server">
    <asp:DropDownList runat="server" id="ColorSelector" autopostback="true" onselectedindexchanged="ColorSelector_IndexChanged">
        <asp:ListItem value="White" selected="True">Select color...</asp:ListItem>
        <asp:ListItem value="Red">Red</asp:ListItem>
        <asp:ListItem value="Green">Green</asp:ListItem>
        <asp:ListItem value="Blue">Blue</asp:ListItem>
    </asp:DropDownList>
    </form>
</body>
</html>

And here is the CodeBehind:


using System;
using System.Data;
using System.Web;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(Session["BackgroundColor"] != null)
        {
            ColorSelector.SelectedValue = Session["BackgroundColor"].ToString();
            BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
        }
    }

    protected void ColorSelector_IndexChanged(object sender, EventArgs e)
    {
        BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
        Session["BackgroundColor"] = ColorSelector.SelectedValue;
    }
}

As you can see, for example, there are not many changes needed to use sessions instead of cookies. Please note that the session value is tied to one instance of your browser. If you close the browser, the saved values ​​(usually) will be "lost"

In addition, if the webserver has redefined the aspnet_wp.exe process, then sessions are lost, because they are also saved in memory. This can be saved by saving the session states on separate state servers or by saving to the SQL Server, but it is beyond the scope of this article.